/**
 * @file 收藏功能
 * @module collect
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires wx-server-sdk - 云函数库
 * @requires config/config - 基础配置
 */
const cloud = require('wx-server-sdk'),
      config = require('../config/config');

// 初始化云函数
cloud.init();
// 数据库实例
const db = cloud.database({
  env: config.env
});

// 操作类型
const OPEARTION_TYPE = {
  'ADD': 'add',
  'DELETE': 'delete'
}

// 收藏列表类型
const COLLECT_TYPE = {
  TOPIC: 'topic',
  SINGLE: 'single'
}

/**
 * @description 收藏主题
 * @param {string} collectType - 收藏类型 
 * @param {string} operation - 操作类型 
 * @param {string} openid - 微信开放ID
 * @param {object} params - 请求参数
 * @returns {object}
 */
const collect = async ({ collectType, operation, openid, params }) => {
  try {
    let { data: [ collect ] } = await db.collection(`user_collect`)
                                        .where({
                                          openid
                                        })
                                        .get();

    let updateId = 0;
                                        
    if (!collect) {
      collect = {
        openid,
        topic: [],
        single: []
      }

      const { _id } = await db.collection(`user_collect`)
                              .add({
                                data: collect
                              });
      updateId = _id;
    } else {
      const { _id } = collect;
      updateId = _id;
    }

    switch (operation) {
      case OPEARTION_TYPE.ADD:
        collect[collectType].push(params);
        break;
      case OPEARTION_TYPE.DELETE:
        const { id } = params;
        collect[collectType] = collect[collectType].filter(item => item.id !== id);
        break;
      default:
        break;
    }

    const { topic, single } = collect;

    await db.collection(`user_collect`)
            .doc(updateId)
            .update({
                data: {
                  topic,
                  single
                }
            });

    return {
      code: 0,
      message: 'operation success.'
    }
  } catch (error) {
    return {
      code: -1,
      message: `operation failed. ${error}`
    }
  }
}

/**
 * @description 查询收藏状态
 * @param {string} collectType - 收藏类型 
 * @param {string} openid - 微信开放ID
 * @param {string} id - 主题ID
 * @returns {object}
 */
const queryCollectStatus = async ({ collectType, openid, id }) => {
  try {
    let { data: [ collect ] } = await db.collection(`user_collect`)
                                        .where({
                                          openid
                                        })
                                        .get();

    const isCollect = collect && collect[collectType].some(item => item.id === id);

    return {
      code: 0,
      message: 'query success.',
      data: {
        isCollect
      }
    }
  } catch (error) {
    return {
      code: -1,
      message: `query failed. ${error}`,
      data: {
        isCollect: false
      }
    }
  }
}

/**
 * @description 查询收藏集
 * @param {string} openid - 微信开放ID 
 * @returns {object}
 */
const queryCollectList = async ({ openid }) => {
  try {
    let { data: [ collect ] } = await db.collection(`user_collect`)
                                        .where({
                                          openid
                                        })
                                        .get();

    return {
      code: 0,
      message: 'query list success.',
      data: {
        collect
      }
    }
  } catch (error) {
    return {
      code: -1,
      message: `query list failed. ${error}`,
      data: {
        collect: {}
      }
    }
  }
}

module.exports = {
  collect,
  queryCollectStatus,
  queryCollectList
}